package utils;

import org.apache.commons.lang.StringUtils;
import play.Logger;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author zhangzc
 * @since 2017/7/26
 */
public class NumberUtil {

    public static String formatAsRMB(long amount){
        if(amount == 0){
            return "0";
        }
        if(amount < 100){
            DecimalFormat df = new DecimalFormat("0.00");
            return df.format(amount / 100d);
        }
        DecimalFormat df = new DecimalFormat("#.00");
        return df.format(amount/100d);
    }

    public static List<Integer> stringToIntList(String ids, Character splitChar){
        if(StringUtils.isEmpty(ids)){
            return Collections.emptyList();
        }
        String[] list = StringUtils.split(ids, splitChar);
        if(list.length == 0){
            return Collections.emptyList();
        }
        List<Integer> r = new ArrayList<>(list.length);
        for(String id: list){
            try{
                Integer i = Integer.parseInt(id);
                if(i != null){
                    r.add(i);
                }
            }catch (Exception e){
                Logger.error(e, "Error in NumberUtil.stringToIntList()");
            }
        }
        return r;
    }

    /**
     * 判断是否是数字类型 包括科学计数法在内
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str)
    {
        if (StringUtils.isBlank(str))
        {
            return false;
        }
        Pattern pattern = Pattern.compile("^[-+]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?[dD]?$");
        return pattern.matcher(str).matches();
    }

    public static String createRandomNum(int len){
        long size = 1;
        for (int i = 0; i < len; i++) {
            size *= 10;
        }

        long num = (long)(Math.random()*size);
        return String.format("%0"+len+"d", num);
    }


    /**
     * Test
     * @param args
     */
    public static void main(String[] args){
        String r = formatAsRMB(0);
        Logger.info("0->%s", r);
        r = formatAsRMB(01);
        Logger.info("0.01->%s", r);
        String num = createRandomNum(6);
        Logger.info("Random->%s", num);
    }
}
